<template>
    <div class="view_category">
        <!-- 左侧 -->
        <card class="left" title="产品分类">
            <el-tree
                :indent="12"
                :data="treeData"
                :props="{ label: 'categoryName', children: 'childs' }"
                node-key="catalogId"
                @node-click="handleTreeNodeClick"
                ref="tree"
            />
        </card>

        <!-- 左侧 -->
        <div class="right">
            <router-view v-if="isContentShowed" />
            <el-alert v-else type="success">请先选择左侧产品分类</el-alert>
        </div>
    </div>
</template>

<script>
// 用于其他路由产品类别判断
let flag = false;

export default {
    data() {
        return {
            treeData: [],
        };
    },

    computed: {
        categoryId() {
            return +this.$route.query.categoryId;
        },

        isContentShowed() {
            return !isNaN(this.categoryId) && typeof this.categoryId === 'number';
        },

        routePath() {
            return this.$route.path;
        },
    },

    methods: {
        handleTreeNodeClick({ catalogId, categoryName, catLevel }) {
            // 是当前id返回
            if (catalogId === this.categoryId) return;

            // 如果是轮播路由或服务协议路由，类别级别无需是3
            if (this.routePath === '/category/banners' || this.routePath === '/category/service_agreements') {
                this.$router.push({ query: { categoryId: catalogId, categoryName } });
                return;
            }

            // 点击的节点类别级别必须是3
            if (catLevel === 3) {
                this.$router.push({ query: { categoryId: catalogId, categoryName } });
            }
        },

        // 获取类别列表
        getCategory() {
            let routePath = this.routePath,
                cb = res => {
                    this.treeData = Object.freeze(res);
                };

            if (routePath === '/category/banners') {
                // 如果是banner路由
                this.$get('/yxl/pms/findBannerCategory').then(cb);
                flag = false;
            } else if (routePath === '/category/service_agreements') {
                // 如果是服务协议路由
                this.$get('/yxl/pms/findProtocolCategory').then(cb);
                flag = false;
            } else {
                // 否则
                if (flag) return;
                this.$get('/yxl/pms/findPmsCategory').then(res => {
                    cb(res);
                    flag = true;
                });
            }
        },
    },

    watch: {
        routePath: {
            handler: 'getCategory',
            immediate: true,
        },
    },

    beforeRouteLeave(to, from, next) {
        // 路由离开初始旗帜；
        flag = false;

        next();
    },
};
</script>